<template>
  <div class="Params">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert title="注意：只允许为第三级分类设置相关属性" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          <p>选择商品分类</p>
          <el-cascader style="width: 40%; margin-top: 10px" v-model="selectedCateKeys" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane :disabled="isDisabled" label="动态参数" name="many">
          <!-- 添加动态参数 -->
          <el-button :disabled="isDisabled" type="primary" size="default" @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" stripe border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand" label="" width="180">
              <template v-slot="scope">
                <!-- 参数标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="180"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name" width="180"> </el-table-column>
            <el-table-column label="操作" width="300">
              <template v-slot="scope">
                <el-button icon="el-icon-edit" :disabled="isDisabled" type="primary" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button icon="el-icon-delete" :disabled="isDisabled" type="danger" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane :disabled="isDisabled" label="静态属性" name="only">
          <!-- 添加静态属性 -->
          <el-button :disabled="isDisabled" type="primary" size="default" @click="addParamsDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyTableData" stripe border style="width: 100%">
            <el-table-column type="expand" label="" width="180">
              <template v-slot="scope">
                <!-- 静态属性标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="180"> </el-table-column>
            <el-table-column label="参数名称" prop="attr_name" width="180"> </el-table-column>
            <el-table-column label="操作" width="400">
              <template v-slot="scope">
                <el-button icon="el-icon-edit" :disabled="isDisabled" type="primary" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button icon="el-icon-delete" :disabled="isDisabled" type="danger" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动/静的对话框 -->
    <el-dialog :title="titleText" :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsDialogClosed">
      <!-- 添加参数的表单 -->
      <el-form :model="addParamsForm" :rules="addParamsRules" label-width="100px" ref="addParamsFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改的对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsDialogClosed">
      <!-- 编辑参数的表单 -->
      <el-form :model="editParamsForm" :rules="editParamsRules" label-width="100px" ref="editParamsFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      // 商品分类列表
      cateList: [],
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 被选中的分类，可能保存一二三级，所以是个数组
      selectedCateKeys: [],
      // 当前选中的标签页
      activeName: "many",
      // 动态参数
      manyTableData: [],
      // 静态参数
      onlyTableData: [],
      // 控制添加参数对话框的显示
      addParamsDialogVisible: false,
      // 添加参数的表单
      addParamsForm: {
        attr_name: "",
      },
      // 添加参数的表单的验证规则
      addParamsRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
      // 是否显示编辑参数对话框
      editParamsDialogVisible: false,
      // 要修改的参数的表单对象
      editParamsForm: {},
      editParamsRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    // 如果未选择三级分类，禁用tab和按钮
    isDisabled() {
      if (this.selectedCateKeys.length !== 3) return true;
      return false;
    },
    // 被选中的商品分类的 id，只能说三级分类
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    // 动态改变对话框的标题
    titleText() {
      if (this.activeName === "many") return "动态参数";
      return "静态属性";
    },
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$request("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，获取商品分类失败");
      }
      this.cateList = res.data;
    },
    // 监听级联选择器选项的变化
    handleChange() {
      this.getParamsData();
      this.manyTableData = [];
      this.onlyTableData = [];
    },
    // tab页签点击事件的处理函数
    handleTabClick() {
      this.getParamsData();
    },
    // 获取动态参数、静态属性
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        return;
      }
      // 根据所选分类的id和当前所处的tab，获取对应的参数
      const { data: res } = await this.$request(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName,
        },
      });
      if (res.meta.status !== 200) return this.$message.error("服务器错误，获取参数失败");
      res.data.forEach((item) => {
        if (!item.attr_vals) {
          item.attr_vals = [];
        } else item.attr_vals = item.attr_vals.split(" ");
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") this.manyTableData = res.data;
      else this.onlyTableData = res.data;
    },
    // 监听添加参数对话框的关闭
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields();
    },

    // 点击按钮添加参数
    addParams() {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$request.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName,
        });
        if (res.meta.status !== 200) this.$message.error("服务器错误，添加参数失败");
        this.$message.success("添加参数成功");
        this.getParamsData();
        this.addParamsDialogVisible = false;
      });
    },
    // 监听编辑参数对话框的关闭
    editParamsDialogClosed() {
      this.$refs.editParamsFormRef.resetFields();
    },
    async showEditDialog(attr_id) {
      // 查询当前参数
      const { data: res } = await this.$request(`categories/${this.cateId}/attributes/${attr_id}`, {
        params: {
          attr_sel: this.activeName,
        },
      });
      if (res.meta.status !== 200) return this.$message.error("服务器错误，获取参数失败");
      this.editParamsForm = res.data;
      this.editParamsDialogVisible = true;
    },
    // 点击按钮修改参数
    editParams() {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$request.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName,
        });
        if (res.meta.status !== 200) {
          return this.$message.error("服务器错误，修改参数失败");
        }
        this.$message.success("修改参数成功");
        this.getParamsData();
        this.editParamsDialogVisible = false;
      });
    },
    // 删除参数
    async removeParams(attr_id) {
      const result = await this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      if (result !== "confirm") return this.$message.info("取消删除");
      const { data: res } = await this.$request.delete(`categories/${this.cateId}/attributes/${attr_id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，删除参数失败");
      }
      this.$message.success("删除参数成功");
      this.getParamsData();
    },
    // 回车键、文本框失去焦点触发添加参数
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.inputValue = row.inputValue.trim();
      row.attr_vals.push(row.inputValue);
      row.inputValue = "";
      row.inputVisible = false;
      this.saveSttrVals(row, "添加参数成功");
    },
    // 点击标签切换到文本框
    showInput(row) {
      // 显示文本框
      row.inputVisible = true;
      // 让文本框自动获取焦点
      // 显示文本框的时候DOM还没有渲染出来
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 保存参数标签
    async saveSttrVals(row, message) {
      const { data: res } = await this.$request.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(" "),
      });
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，添加参数标签失败");
      }
      this.$message.success(message);
    },
    // 删除参数标签
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveSttrVals(row, "删除参数成功");
    },
  },
};
</script>

<style lang="less" scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
